/* Filename: primerN.c
 * Description: N进程,交叉分配区间内的数进行计算(并且等待回收进程)
 * Last modified: humble 20200322 17:05
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define LEFT (30000000)
#define RIGHT (30000200)
#define N (3)

static void usage(void);

int main(int argc, char **argv) {
    if(argc != 1){ fprintf(stderr, "argc !=1"); usage(); exit(1); }
    int mark;
    pid_t pid;
    for(int n = 0; n < N; n++) {
        pid = fork();
        if(pid < 0){ perror("fork()"); exit(1); } //TODO 如果已成功创建了2个，就得收尸2个
        else if(pid == 0){
            for(int i = LEFT + n; i < RIGHT; i+=N) { // 此时n为0的子进程永远拿不到质数
                mark = 1;
                for(int j = 2; j < i/2; j++) {
                    if(i % j == 0){ mark = 0; break; }
                }
                if(mark == 1){ printf("[%d] %d is a primer\n", n, i); }
            }
            exit(0);
        }
        else{ continue; } //父进程
    }

    //int st;
    for(int n = 0; n < N; n++) {
        // wait(&st); printf("%d\n", st); //等同waitpid(-1, &st, 0);
        wait(NULL); // 不关心返回状态用NULL 
    }
    return 0;
}

static void usage(void) {
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
